package com.yic.module.mes.controller.admin.reportworkhours;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yic.framework.common.util.collection.CollectionUtils;
import com.yic.module.base.api.factory.FactoryApi;
import com.yic.module.base.api.factory.dto.FactoryRespDTO;
import com.yic.module.base.api.item.ItemApi;
import com.yic.module.base.api.item.dto.ItemRespDTO;
import com.yic.module.base.api.workshop.WorkshopApi;
import com.yic.module.base.api.workshop.dto.WorkshopRespDTO;
import com.yic.module.mes.dal.dataobject.process.ProcessDO;
import com.yic.module.mes.service.process.ProcessService;
import com.yic.module.system.api.user.AdminUserApi;
import com.yic.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import com.yic.framework.common.pojo.PageResult;
import com.yic.framework.common.pojo.CommonResult;
import static com.yic.framework.common.pojo.CommonResult.success;

import com.yic.framework.excel.core.util.ExcelUtils;

import com.yic.framework.operatelog.core.annotations.OperateLog;
import static com.yic.framework.operatelog.core.enums.OperateTypeEnum.*;

import com.yic.module.mes.controller.admin.reportworkhours.vo.*;
import com.yic.module.mes.dal.dataobject.reportworkhours.ReportWorkHoursDO;
import com.yic.module.mes.convert.reportworkhours.ReportWorkHoursConvert;
import com.yic.module.mes.service.reportworkhours.ReportWorkHoursService;

@Tag(name = "管理后台 - 报工工时")
@RestController
@RequestMapping("/mes/report-work-hours")
@Validated
public class ReportWorkHoursController {

    @Resource
    private ReportWorkHoursService reportWorkHoursService;
    @Resource
    private FactoryApi factoryApi;
    @Resource
    private WorkshopApi workshopApi;
    @Resource
    private ItemApi itemApi;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private ProcessService processService;

    @PostMapping("/create")
    @Operation(summary = "创建报工工时")
    @PreAuthorize("@ss.hasPermission('mes:report-work-hours:create')")
    public CommonResult<Long> createReportWorkHours(@Valid @RequestBody ReportWorkHoursCreateReqVO createReqVO) {
        return success(reportWorkHoursService.createReportWorkHours(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新报工工时")
    @PreAuthorize("@ss.hasPermission('mes:report-work-hours:update')")
    public CommonResult<Boolean> updateReportWorkHours(@Valid @RequestBody ReportWorkHoursUpdateReqVO updateReqVO) {
        reportWorkHoursService.updateReportWorkHours(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除报工工时")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:report-work-hours:delete')")
    public CommonResult<Boolean> deleteReportWorkHours(@RequestParam("id") Long id) {
        reportWorkHoursService.deleteReportWorkHours(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得报工工时")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:report-work-hours:query')")
    public CommonResult<ReportWorkHoursRespVO> getReportWorkHours(@RequestParam("id") Long id) {
        ReportWorkHoursDO reportWorkHours = reportWorkHoursService.getReportWorkHours(id);
        return success(ReportWorkHoursConvert.INSTANCE.convert(reportWorkHours));
    }

    @GetMapping("/list")
    @Operation(summary = "获得报工工时列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('mes:report-work-hours:query')")
    public CommonResult<List<ReportWorkHoursRespVO>> getReportWorkHoursList(@RequestParam("ids") Collection<Long> ids) {
        List<ReportWorkHoursDO> list = reportWorkHoursService.getReportWorkHoursList(ids);
        return success(ReportWorkHoursConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得报工工时分页")
    @PreAuthorize("@ss.hasPermission('mes:report-work-hours:query')")
    public CommonResult<PageResult<ReportWorkHoursRespVO>> getReportWorkHoursPage(@Valid ReportWorkHoursPageReqVO pageVO) {
        PageResult<ReportWorkHoursDO> pageResult = reportWorkHoursService.getReportWorkHoursPage(pageVO);
        return success(ReportWorkHoursConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出报工工时 Excel")
    @PreAuthorize("@ss.hasPermission('mes:report-work-hours:export')")
    @OperateLog(type = EXPORT)
    public void exportReportWorkHoursExcel(@Valid ReportWorkHoursExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<ReportWorkHoursDO> list = reportWorkHoursService.getReportWorkHoursList(exportReqVO);
        // 导出 Excel
        List<ReportWorkHoursExcelVO> datas = ReportWorkHoursConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "报工工时.xls", "数据", ReportWorkHoursExcelVO.class, datas);
    }


    @GetMapping("/forms")
    @Operation(summary = "获得报工工时报表")
    @PreAuthorize("@ss.hasPermission('mes:report-work-hours:forms')")
    public CommonResult<List<ReportWorkHoursFormsRespVO>> getReportWorkHoursExcel(@Valid ReportWorkHoursFormsReqVO reqVO) {
        List<ReportWorkHoursFormsRespVO> list = reportWorkHoursService.getReportWorkHoursForms(reqVO);
        //封装数据
        if (CollectionUtil.isNotEmpty(list)) {
            //提取工厂数据
            Set<Long> factoryIds = CollectionUtils.convertSet(list, ReportWorkHoursFormsRespVO::getFactoryId);
            List<FactoryRespDTO> factoryRespDTOS = factoryApi.getFactoryList(factoryIds);
            Map<Long, FactoryRespDTO> factoryMap = CollectionUtils.convertMap(factoryRespDTOS, FactoryRespDTO::getId);
            //提取车间数据
            Set<Long> workshopIds = CollectionUtils.convertSet(list, ReportWorkHoursFormsRespVO::getWorkshopId);
            List<WorkshopRespDTO> workshopRespDTOS = workshopApi.getWorkshopList(workshopIds);
            Map<Long, WorkshopRespDTO> workshopMap = CollectionUtils.convertMap(workshopRespDTOS, WorkshopRespDTO::getId);
            //提取产品数据
            Set<Long> itemIds = CollectionUtils.convertSet(list, ReportWorkHoursFormsRespVO::getItemId);
            List<ItemRespDTO> itemRespDTOS = itemApi.getItemList(itemIds);
            Map<Long, ItemRespDTO> itemMap = CollectionUtils.convertMap(itemRespDTOS, ItemRespDTO::getId);
            //查询用户信息
            Set<Long> userIds = CollectionUtils.convertSet(list, ReportWorkHoursFormsRespVO::getUserId);
            List<AdminUserRespDTO> userRespDTOS = adminUserApi.getUserList(userIds);
            Map<Long, AdminUserRespDTO> userMap = CollectionUtils.convertMap(userRespDTOS, AdminUserRespDTO::getId);
            //提取工艺信息
            Set<Long> processIds = CollectionUtils.convertSet(list, ReportWorkHoursFormsRespVO::getProcessId);
            List<ProcessDO> processList = processService.getProcessList(processIds);
            Map<Long, ProcessDO> processMap = CollectionUtils.convertMap(processList, ProcessDO::getId);
            list.forEach(tmp -> {
                FactoryRespDTO factory = factoryMap.get(tmp.getFactoryId());
                if (ObjectUtil.isNotEmpty(factory)) {
                    tmp.setFactoryName(factory.getName());
                }
                WorkshopRespDTO workshop = workshopMap.get(tmp.getWorkshopId());
                if (ObjectUtil.isNotEmpty(workshop)) {
                    tmp.setWorkshopName(workshop.getName());
                }
                ItemRespDTO item = itemMap.get(tmp.getItemId());
                if (ObjectUtil.isNotEmpty(item)) {
                    tmp.setItemCode(item.getCode());
                    tmp.setItemName(item.getName());
                    tmp.setItemSpec(item.getSpec());
                    tmp.setDrawCode(item.getDrawCode());
                }
                AdminUserRespDTO user = userMap.get(tmp.getUserId());
                if (ObjectUtil.isNotEmpty(user)) {
                    tmp.setUserName(user.getNickname());
                }
                ProcessDO process = processMap.get(tmp.getProcessId());
                if (ObjectUtil.isNotEmpty(process)) {
                    tmp.setProcessName(process.getName());
                }
            });
        }
        return success(list);
    }

}
